package com.mikufufu.blog.common.language;

import com.mikufufu.blog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Slf4j
public class HeaderLocaleResolver implements LocaleResolver {

    @NotNull
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 优先从自定义请求头 "X-Lang" 获取语言标识
        String langHeader = request.getHeader("X-Lang");
        if (StringUtils.isNotBlank(langHeader)) {
            return parseLocale(langHeader);
        }
        //  检查URL参数（?lang=zh_CN）
        String paramLang = request.getParameter("lang");
        if (StringUtils.isNotBlank(paramLang)) {
            return parseLocale(paramLang);
        }
        // 获取浏览器语言
        Locale locale = request.getLocale();
        if (locale != null) {
            return locale;
        }
        // 获取中文
        return Locale.CHINA;
    }

    private Locale parseLocale(String lang) {
        try {
            return Locale.forLanguageTag(lang.replace('_', '-'));
        } catch (Exception e) {
            log.error("解析语言失败：{}", lang, e);
            return Locale.CHINA;
        }
    }

    @Override
    public void setLocale(@NotNull HttpServletRequest request, HttpServletResponse response, Locale locale) {
        // 无需实现
    }
}
